package SpgBI_Dec.Common;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBUtils {
    private static HashMap<String, ComboPooledDataSource> dataSources = new HashMap<String, ComboPooledDataSource>();

    private synchronized static ComboPooledDataSource getDataSource(String dsName) {
        ComboPooledDataSource ds = dataSources.get(dsName);
        if (ds == null) {
            try {
                ds = new ComboPooledDataSource(dsName);
                dataSources.put(dsName, ds);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("创建连接池失败：" + dsName);
            }
        }

        return ds;
    }

    public static Connection getConnection(String dsName) {
        ComboPooledDataSource ds = getDataSource(dsName);
        Connection conn = null;
        try {
            conn = ds.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取连接失败：" + dsName);
        }
        return conn;
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }


    /**
     * 通用取结果方案,返回JSONArray
     *
     * @param rs
     * @return
     * @throws SQLException
     */

    public static JSONArray extractJSONArray(ResultSet rs) throws SQLException {
        ResultSetMetaData md = rs.getMetaData();
        int num = md.getColumnCount();
        JSONArray array = new JSONArray();
        while (rs.next()) {
            JSONObject mapOfColValues = new JSONObject();
            for (int i = 1; i <= num; i++) {
                mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
            }

            array.put(mapOfColValues);
        }
        return array;
    }

    /**
     * 通用取结果方案,返回list
     *
     * @param rs
     * @return
     * @throws SQLException
     */
    public static List ExtractData(ResultSet rs) throws SQLException {
        ResultSetMetaData md = rs.getMetaData();
        int num = md.getColumnCount();
        List listOfRows = new ArrayList();
        while (rs.next()) {
            Map mapOfColValues = new HashMap(num);
            for (int i = 1; i <= num; i++) {
                mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
            }
            listOfRows.add(mapOfColValues);
        }
        return listOfRows;
    }

}


